import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../lib_basemodel/user/user.dart';
import '../lib_baseview/provider.dart';
import '../lib_runtime/event_bus.dart';
import '../lib_runtime/event_center.dart';
import '../lib_runtime/event_constant.dart';
import '../lib_runtime/global_config.dart';
import '../lib_user/user_manager.dart';

class MainPageModel extends JRChangeNotifier {
  // late Resources resource;

  static MainPageModel instance = _instance;

  factory MainPageModel() => _instance;
  static final MainPageModel _instance = MainPageModel._internal();

  StreamSubscription<Event>? _eventSub;
  StreamSubscription? sub;

  MainPageModel._internal() {
    // MessageNotifier.instance.registerCallback(EaseCmdPushType.CAR_FLYING_SCREEN.name,
    //     (EaseCmdPush message) {
    //       RoomFlyingScreen roomFlyingScreen = message.content.unpackInto(RoomFlyingScreen());
    //       MainPageModel.instance.addGlobalAnimation(roomFlyingScreen);
    // });
  }

  initData() async {
    UserManager.instance.currentUser;
    requestSettings();
    requestResource();
    _eventSub = eventCenter.subscribe(EventConstant.refreshWishTag).listen(_onReceiveEvent);
    sub = eventBus.on<JumpToDiscoverAction>().listen((event) {
      Get.until((route) {
        return route.settings.name == "/";
      });
      onNavigationBarClick(1);
    });
  }

  // List<RoomFlyingScreen> dataNeedToPlay = [];
  // RoomFlyingScreen? currentAnimationData;
  // AnimationController? carAnimationController;
  // late Animation animations;
  // AnimationController? giftAnimationController;
  // late Animation giftAnimations;

  //初始化礼物动画controller(由于需要SingleTickerProviderStateMixin，因此在initState调用)
  initGlobalAnimationController(
      TickerProviderStateMixin singleTickerProviderStateMixin,
      BuildContext context) {
    // carAnimationController = AnimationController(
    //     vsync: singleTickerProviderStateMixin,
    //     duration: const Duration(milliseconds: 4000));
    TweenSequence tweenSequence = TweenSequence([
      TweenSequenceItem(
          tween: Tween<double>(begin: 0.0, end: 0.5), weight: 125),
      TweenSequenceItem(
          tween: Tween<double>(begin: 0.5, end: 0.5), weight: 775),
      TweenSequenceItem(
          tween: Tween<double>(begin: 0.5, end: 1.0), weight: 100),
    ]);

    // animations = tweenSequence.animate(carAnimationController!);

    // carAnimationController!.addStatusListener((status) {
    //   if (status == AnimationStatus.completed) {
    //     checkAnimation();
    //   }
    // });
    // giftAnimationController = AnimationController(
    //     vsync: singleTickerProviderStateMixin,
    //     duration: const Duration(milliseconds: 4000));

    // giftAnimations = tweenSequence.animate(giftAnimationController!);

    // giftAnimationController!.addStatusListener((status) {
    //   if (status == AnimationStatus.completed) {
    //     checkAnimation();
    //   }
    // });
  }

  void checkAnimation() async {
    if (!GlobalConfig.hasEnterMainPage) {
      return;
    }
    // if (dataNeedToPlay.isNotEmpty) {
    //   currentAnimationData = dataNeedToPlay[0];
    //   if (currentAnimationData != null &&
    //       currentAnimationData!.type == FlyingScreenType.CAR) {
    //     dataNeedToPlay.removeAt(0);
    //     notifyListeners();
    //     carAnimationController?.forward(from: 0);
    //   } else if (currentAnimationData != null &&
    //       currentAnimationData!.type == FlyingScreenType.GIFT) {
    //     dataNeedToPlay.removeAt(0);
    //     notifyListeners();
    //     giftAnimationController?.forward(from: 0);
    //   }
    // }
  }

  // void addGlobalAnimation(RoomFlyingScreen data) {
  //   if(!GlobalConfig.hasEnterMainPage){
  //     return;
  //   }
  //   dataNeedToPlay.add(data);
  //   if (!(carAnimationController!.status == AnimationStatus.completed ||
  //           carAnimationController!.status == AnimationStatus.dismissed) ||
  //       !(giftAnimationController!.status == AnimationStatus.completed ||
  //           giftAnimationController!.status == AnimationStatus.dismissed)) {
  //     return;
  //   }
  //   checkAnimation();
  // }

  int currentBottomBarIndex = 0;

  // static Resources? businessUrl;
  // static bool inTeen = false;

  // /// 我喜欢
  // late List<LabelItem> likeLabels;

  /// 我想要
  // late List<LabelItem> wantLabels;

  Map<int, bool> bottomBarIndexRefreshState = {};

  onNavigationBarClick(int index, {bool isSkipRequestUserInfo = false}) {
    if (!isSkipRequestUserInfo) {
      UserManager.instance.refreshUserInfo();
    }
    if (currentBottomBarIndex == index) {
      // refresh
      bottomBarIndexRefreshState[index] = true;
    } else {
      GlobalConfig.bottomBarIndex = index;
      eventCenter.emit(Event(EventConstant.bottomBarIndexChanged));
    }
    currentBottomBarIndex = index;
    notifyListeners();
  }

  var mainPageScaffoldkey = new GlobalKey<ScaffoldState>();

  bool isShowingEndDrawer = false;

  updateIsShowingEndDrawer(bool isOpen) {
    isShowingEndDrawer = isOpen;
    notifyListeners();
  }

  requestSettings() async {
    // await GlobalConfig.refreshSettings(force: true);
    // GetSettingsResp? settingsRsp = GlobalConfig.settingsResp;
    // if(settingsRsp!=null){

    //   inTeen = settingsRsp.isTeenagerMode;

    //   likeLabels = settingsRsp.likeLabels;
    //   wantLabels = settingsRsp.wantLabels;

    //   /// 99 兜风价格, 黄金
    //   rideBasePrice = settingsRsp.rideToPrice["Basic"]!;
    //   /// 199 兜风价格, 铂金
    //   rideStandardPrice = settingsRsp.rideToPrice["Standard"]!;
    //   /// 299 兜风价格，钻石
    //   ridePremiumPrice = settingsRsp.rideToPrice["Premium"]!;

    //   notifyListeners();
    // }
  }

  /*
  List<LabelItem> like = [];
  List<LabelItem> selectLike = [];
  List<LabelItem> want = [];
  List<LabelItem> selectWant = [];
  */
  // requestPostSettings() async {
  //   SetSettingsReq req = SetSettingsReq();
  //
  //   /// 返回信息
  //   GetSettingsResp? settingsRsp;
  //
  //   var resp = await AppApi.instance.postSettings(req);
  //   if(!resp.isSuccess){
  //     showToast("${resp.errorMsg}");
  //     return;
  //   }
  //
  //   if(resp!=null && resp.isSuccess && resp.data!=null){
  //     settingsRsp = resp.data;
  //
  //     inTeen = settingsRsp!.isTeenagerMode;
  //
  //     likeLabels = settingsRsp!.likeLabels;
  //     wantLabels = settingsRsp!.wantLabels;
  //
  //     rideToPrice = settingsRsp!.rideToPrice;
  //
  //     notifyListeners();
  //   }
  //
  //
  // }

  /// 根据标签检查是否有活动中的房间

  requestResource() async {
    // resource = (await Resource.instance
    //         .getTeenResourceData(ResourceType.TEENAGER_MODE))
    //     .data!;
    // businessUrl = (await Resource.instance
    //         .getTeenResourceData(ResourceType.RIDE_HOUSE_KEEPER))
    //     .data!;
    // notifyListeners();
  }

  requestCancelTeen() async {
    // await UserApi.instance.cancelTeenagerPassword();
  }

  bool isShowBottom = true;

  void changeBottomState(state) {
    isShowBottom = state;
    notifyListeners();
  }

  void _onReceiveEvent(Event event) {
    if (event.name == EventConstant.refreshWishTag) {
      requestSettings();
    }
  }

  @override
  void dispose() {
    _eventSub?.cancel();
    sub?.cancel();
    super.dispose();
  }

  void resetBottomBarIndexState(int index) {
    bottomBarIndexRefreshState[index] = false;
    notifyListeners();
  }
}

class GlobalAnimationData {
  String url;
  User? user;

  GlobalAnimationData(this.url, {this.user});
}
